//
//  HtmlAnalysisHelper.m
//  NJUSTHelper
//
//  Created by 郑越辉 on 2017/9/14.
//  Copyright © 2017年 njust. All rights reserved.
//

#import "HtmlAnalysisHelper.h"
#import <ASIFormDataRequest.h>
#import <TFHpple.h>
#import "DefineURL.h"
#import "Define.h"
#import "ScheduleModel.h"
#import "CourseDBService.h"
#import "ScheduleDBService.h"
@implementation HtmlAnalysisHelper


+(NSData *) dataFromUrlString:(NSString *) urlStr
{
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    
    [request startSynchronous];
    
    return [request responseData];
}

+(NSData *) loginDataWithUserID:(NSString *)userId Password:(NSString *) password
{
    [ASIFormDataRequest setSessionCookies:nil];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[BASE_URL stringByAppendingString:LOGIN_URI]]];
    
    [request setPostValue:userId forKey:@"USERNAME"];
    [request setPostValue:password forKey:@"PASSWORD"];
    [request startSynchronous];
    
    return [request responseData];
}
+(NSString *) loginStringWithUserID:(NSString *)userId Password:(NSString *) password
{
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[BASE_URL stringByAppendingString:LOGIN_URI]]];
    
    [request setPostValue:userId forKey:@"USERNAME"];
    [request setPostValue:password forKey:@"PASSWORD"];
    [request startSynchronous];
    
    return [request responseString];
}

+(ASIFormDataRequest *) requestForLogin
{
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[BASE_URL stringByAppendingString:LOGIN_URI]]];
    
    [request setPostValue:AccountInfo.userId forKey:@"USERNAME"];
    [request setPostValue:AccountInfo.password forKey:@"PASSWORD"];
    [request startSynchronous];
    
    return request;
}

+(ASIFormDataRequest *) requestForSchedule
{
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[BASE_URL stringByAppendingString:SCHEDULE_URI]]];
    [request startSynchronous];
    return request;
}

+(BOOL) analysiScheduleAndSave{
    ///登录教务处
    NSString *loginStr = [HtmlAnalysisHelper loginStringWithUserID:AccountInfo.userId Password:AccountInfo.password];
    if(![HtmlAnalysisHelper checkLoginSuccessWithLoginStr:loginStr]) {
        return NO;
    }
    ///获取课表HTML
    ASIFormDataRequest *req = [HtmlAnalysisHelper requestForSchedule];
//    NSString *html4schedule = [req responseString];
//    NSLog(@"---课表信息-----:\n%@", html4schedule);
    
    
    
    TFHpple *htmls = [[TFHpple alloc]initWithHTMLData:[req responseData] encoding:@"UTF8"];
    ///获取课程详情的table,根据id查询全局只有1个, count = 1
    NSArray *tableArray = [htmls searchWithXPathQuery:GET_ALL_COURSE_TABLE];
    ///所有课程详情数组
    NSMutableArray *allCourseArray = [NSMutableArray array];
    ///只循环一次
    for (TFHppleElement * tableElement in tableArray) {
        ///获取table的content并去除换行回车
        NSString *allCourseWithoutEndl  = [[tableElement raw] clearEndl];
        ///每个课程详情的tr
        NSArray *allCourseTrArray = [allCourseWithoutEndl componentsMatchedByRegex:REGEX_TABLE_COURSE_TR];
        ///解析每个课程,并转化为Course Model,保存到数组
        for (NSString *cstr in allCourseTrArray) {
            
            CourseModel *course = [[CourseModel alloc]init];
            course.userId = AccountInfo.userId;
            course.courseId = [NSString getRandomStringWithLength:32];
            ///获取课程的每个属性
            NSArray *tdArray = [cstr componentsMatchedByRegex:REGEX_TABLE_TR_DATA_TD];
            
            for (NSString *dataStr in tdArray) {
                switch ([tdArray indexOfObject:dataStr] + 1) {
                    case 1:///课程号
                        course.courseNum = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 2:///课序号
                        
                        break;
                    case 3:///课程名称
                        course.courseName = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 4:///教师
                        course.teacher = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 5:///时间
                        course.timeStr = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 6:///学分
                        course.score = [[[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets] floatValue];
                        break;
                    case 7:///地点
                        course.placeStr = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 8:///课程属性
                        course.courseAttr = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    case 9:///选课阶段
                        course.courseStage = [[dataStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                        break;
                    default:
                        break;
                }
            }
            [allCourseArray addObject:course];
            
        }
    }
    
    ///存放课表每个单元
    NSMutableArray *scheduleRecordArray = [NSMutableArray array];
    
    ///获取课表每个大节所在的div所对应的input
    ///数组长度必然为42, count = 5(大节) * 7(一周) + 1(中午,PS:网页有的,貌似就没有安排中午的) * 7(一周), 所以解析时可以丢弃最后7个
    NSArray * dataArray = [htmls searchWithXPathQuery:[NSString stringWithFormat:@"//input[@name='%@']", SCHEDULE_DIV_OF_INPUT_NAME]] ;
    ///遍历课表每个单元
    for (int i = 0; i < dataArray.count; i++) {
        TFHppleElement * inputElement  = dataArray[i];
        NSString *divId = [inputElement.attributes objectForKey:@"value"];
        
        if([divId length] > 0) {
            ///获取到当前大节div数组,由于使用id标签, count = 1
            NSArray *scheduleDivArray = [htmls searchWithXPathQuery:[NSString stringWithFormat:@"//div[@id='%@']",divId]];
            NSInteger weekDay = i % 7;
            NSInteger sectionNum = i / 7;
            //只循环一次
            for (TFHppleElement *scheduleDivElement in scheduleDivArray) {
                
                ///课表单元的内部数据
                NSString *content = [[scheduleDivElement raw] clearEndl];
                ///同一单元不同时间课程数组
                NSArray *cdataArray = [content componentsSeparatedByString:REGEX_SPLIT_SCHEDULE_CELL];
                ///遍历每个课程,>=1次
                for (NSString *temp in cdataArray) {
                    ///课表记录
                    ScheduleModel *scheduleCell = [[ScheduleModel alloc]init];
                    scheduleCell.weekDay = weekDay;
                    scheduleCell.sectionNum = sectionNum;
                    scheduleCell.userId = AccountInfo.userId;
                    ///课程名称
                    NSString * courseName = [[temp firstMatchWithPattern:REGEX_COURSE_NAME] clearBrackets];
                    scheduleCell.courseName = courseName;
                    ///课程分组
                    NSString * courseGroup = [[[temp firstMatchWithPattern:REGEX_COURSE_GROUP] firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                    scheduleCell.courseGroup = courseGroup;
                    ///授课教师
                    NSString *teacher = [[[temp firstMatchWithPattern:REGEX_COURSE_TEACHER] firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                    scheduleCell.teacher = teacher;
                    ///上课周次
                    NSString *timeStr = [temp firstMatchWithPattern:REGEX_COURSE_TIME];
                    //课表展示str
                    timeStr = [[timeStr firstMatchWithPattern:REGEX_GENERAL] clearBrackets] ;
                    scheduleCell.timeStr = timeStr;
                    
                    timeStr = [timeStr stringByReplacingOccurrencesOfString:@"(周)" withString:@""];
                    
                    scheduleCell.weekNum = [timeStr integerTransformWithInteger:0];
                    
                    ///上课地点
                    NSString *place = [[[temp firstMatchWithPattern:REGEX_COURSE_PLACE] firstMatchWithPattern:REGEX_GENERAL] clearBrackets];
                    scheduleCell.placeStr = place;
                    
                    for (CourseModel *c in allCourseArray) {
                        ///&& [c.teacher isEqualToString:scheduleCell.teacher]
                        if([c.courseName isEqualToString:scheduleCell.courseName] ){
                            scheduleCell.courseNum = c.courseNum;
                            scheduleCell.courseId = c.courseId;
                            scheduleCell.score = c.score;
                            scheduleCell.courseAttr = c.courseAttr;
                            scheduleCell.courseStage = c.courseStage;
                            c.courseGroup = scheduleCell.courseGroup;
                            
                        }
                    }
                    [scheduleRecordArray addObject:scheduleCell];
                }
                ///该单元格遍历结束
            }
        }
        ///遍历第i个单元格结束
    }
    ///遍历所有单元格结束
    ///将数据写入数据库,先清空该用户的课程
    [CourseDBService removeAllCourse4UserId:AccountInfo.userId];
    [CourseDBService addCoursesToDataBaseWithModel:allCourseArray];
//    NSArray *courses = [CourseDBService getAllCourseByUserId:AccountInfo.userId];
    
    
    [ScheduleDBService removeAllSchedule4UserId:AccountInfo.userId];
    [ScheduleDBService addSchedulesToDataBaseWithModel:scheduleRecordArray];
//    NSArray *schedules = [ScheduleDBService getAllScheduleByUserId:AccountInfo.userId];
    
    return  YES;
}

+(BOOL)checkLoginSuccessWithLoginStr:(NSString *)loginStr {
    if([[loginStr firstMatchWithPattern:@"用户名或密码错误"] length] > 0 || [[loginStr firstMatchWithPattern:@"打开新窗口"] length] > 0 || [[loginStr firstMatchWithPattern:@"用户名或密码不能为空"] length] > 0) {
        return NO;
    }
    return YES;
}


@end
